<?php
/**
 * vim: et ts=4 sts=4 sw=4 fdm=marker
 *
 * 测试controller 
 *
 * @author	wang Penghai <china_php@hotmail.com>
 * @copyright 2008 5e6d Corporation.
 * @version   $Id: config.php 29 2009-03-10 14:30:18Z wph $
 */
pf_load::init('admin_class_admin');
class content_action extends pf_controller{
	protected $category_obj = null;

	public function __construct()
	{ 
		parent::__construct();
		$this->category_obj = pf_load::init('content_model_category');
		$this->content_obj = pf_load::init('content_model_content');
	}

	public function index()
	{
		$category_list = $this->category_obj->get_category_list();
		$content_list = $this->content_obj->get_content_list();
		foreach ($content_list as $key=>$val)
		{
			$fid = $val['fid'];
			$fpid = $val['fpid'];
			$content_list[$key]['fname'] = $content_list[$key]['fpname'] = '无';
			foreach ($category_list as $k=>$v)
			{
				if ($v['id'] == $fid)
				{
					$content_list[$key]['fname'] = $v['name'];
				}
				if ($v['id'] == $fpid)
				{
					$content_list[$key]['fpname'] = $v['name'];
				}
			}
		}
		$this->assign('content_list', $content_list);
		$this->view('content_admin_view_content.list');
	}

	public function add()
	{
		$opt = pf_request::get('opt', 'list');
		switch ($opt)
		{
			case 'insert':
				$this->insert();
				break;
			case 'update':
				$this->update();
				break;
			default:
				$this->show_add();
				break;
		}
		
	}

	public function show_add()
	{
		$category_list = $this->get_category_list();
		$this->assign('category_list', $category_list);
		$this->view('content_admin_view_content.add');
	}

	private function get_category_list()
	{
		$category_list = $this->category_obj->get_category_list();
		foreach ($category_list as $key=>$val)
		{
			$level = $val['level'];
			$str = '';
			if ($level > 1)
			{
				$str = "└";
				for($i=0; $i < $level; $i++)
				{
					$str .= '--';
				}
			}
			$category_list[$key]['name'] = $str . $category_list[$key]['name'];
		}
		return $category_list;
	}
	
	public function update()
	{
		$data['parentid'] = (int)pf_request::post('parentid', 0);
		$data['name'] = pf_request::post('cname', '');

		//$time = time();
		//$data['updatetime'] = $time;
		$id = pf_request::post('id', 0);
		$argv = array(
			'data'=> $data,
			'where' => 'id=' . (int)$id,
		);

		$res = $this->category_obj->update($argv);
		if (false === $res)
		{
			echo "fail";
		} else {
			echo "success";
		}
	}

	public function insert()
	{
		$data['fid'] = (int)pf_request::post('category', 0);
		$data['subject'] = pf_request::post('title');
		$data['summary'] = pf_request::post('summary');
		$data['content'] = pf_request::post('content1');
		$data['tags'] = pf_request::post('tags');
		
		//获取父id；
		$fres = $this->category_obj->get_pid_by_id($data['fid']);
		$data['fpid'] = (int)$fres;
		$time = time();
		$data['lastpost'] = $data['posttime'] = $time;
		$res = $this->content_obj->insert($data);
		if (false === $res)
		{
			echo "fail";
		} else {
			echo "success";
		}
	}
}
